package org.lisen.patterndemo.singleton;

/**
 * 单例模式： 懒汉式, 有线程问题
 */
public class SingletonDemo02 {

    private SingletonDemo02(){
        //模拟构造函数的运行耗时
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static SingletonDemo02 singletonDemo02 = null;

    public static SingletonDemo02 getInstance() {

        if (singletonDemo02 == null) {

            singletonDemo02 = new SingletonDemo02();
        }

        return singletonDemo02;
    }

    public String hello(String name) {
        return "hello " + name;
    }

    /*
     * 测试多线程下单例模式是否安全
     * @param args
     */
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                System.out.println(SingletonDemo02.getInstance().hashCode());
            }).start();
        }
    }

}